<?php
namespace app\helper\tools;

use Base64Url\Base64Url;

class Security
{

    const METHOD_AES_128_CBC = 'AES-128-CBC';

    /**
     * 加密
     * @param $input
     * @param $key
     * @param bool $url
     * @return string
     */
    public static function encrypt($input, $key, $url = false)
    {
        $size = openssl_cipher_iv_length(self::METHOD_AES_128_CBC);
        $iv = openssl_random_pseudo_bytes($size, $secure);
        if (false === $secure || false === $iv) {
            throw new \RuntimeException('iv generation failed');
        }

        $data = openssl_encrypt($input, self::METHOD_AES_128_CBC, $key, OPENSSL_RAW_DATA, $iv);

        if ($url) {
            return Base64Url::encode($iv . $data);
        }

        return base64_encode($iv . $data);
    }

    /**
     * 解密
     * @param $sStr
     * @param $key
     * @param bool $url
     * @return string
     */
    public static function decrypt($sStr, $key, $url = false)
    {
        $size = openssl_cipher_iv_length(self::METHOD_AES_128_CBC);
        if ($url) {
            $sStr = Base64Url::decode($sStr);
        } else {
            $sStr = base64_decode($sStr);
        }
        $iv = substr($sStr, 0, $size);
        $sStr = substr($sStr, $size);

        $data = openssl_decrypt($sStr, self::METHOD_AES_128_CBC, $key, OPENSSL_RAW_DATA, $iv);

        return $data;
    }
}
